package com.librariy.net;

import java.io.ByteArrayInputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

import com.librariy.util.Log;
import com.librariy.util.UIHelper;

import android.graphics.Bitmap;
import android.net.http.SslCertificate;
import android.net.http.SslError;
import android.os.Bundle;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class SSLWebViewClient extends WebViewClient {
    private static final String TAG = "SSLWebViewClient";
    
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        Log.d(TAG, "onPageStarted(), URL=" + url + "");
    }
    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);
    }
    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        Log.e(TAG, "onReceivedSslError=" + error.toString());
        if (trust(error.getCertificate())) {
            handler.proceed();
        } else {
            super.onReceivedSslError(view, handler, error);
            UIHelper.showToast(view.getContext(), "该网页证书有问题，已取消加载！");
        }
    }

    private boolean trust(SslCertificate mSslCertificate) {
        try {
            Bundle mData = SslCertificate.saveState(mSslCertificate);
            byte[] bytes = mData.getByteArray("x509-certificate");
            if (bytes == null)
                return false;
            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(bytes));
            KeyStore mKeyStore = SSLManager.buildTrustKeyStore();
            Enumeration<String> aliases = mKeyStore.aliases();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                if(!alias.startsWith("User-Trust-Certificate")){
                    continue;
                }
                if (!mKeyStore.isCertificateEntry(alias)) {
                    continue;
                }
                Certificate c = mKeyStore.getCertificate(alias);
                cert.verify(c.getPublicKey());
                return true;
            }
            return false;
        } catch (Exception e) {
            Log.e(TAG,"trust",e);
            return false;
        }
    }
}
